package com.xiaoger.async.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 异步任务执行类
 *
 * @author xjx
 * @date 2022/5/11 16:31
 */
@Component
public class AsyncTask {

    private static final Logger logger = LoggerFactory.getLogger(AsyncTask.class);

    @Async
    public void firstAsyncTask() throws InterruptedException {
        logger.info("返回值为void的异步方法调用开始,线程为：{}", Thread.currentThread().getName());
        long startTime = System.currentTimeMillis();
        Thread.sleep(2000);
        long endTime = System.currentTimeMillis();
        logger.info("异步方法执行耗时{}ms", endTime - startTime);
        logger.info("返回值为void的异步方法调用结束,线程为：{}", Thread.currentThread().getName());
    }

    /**
     * 带参数和返回值的异步任务
     */
    @Async
    public Future<List<Integer>> secondAsyncTask(Integer value) {
        logger.info("带参数和返回值的异步任务开始执行，线程为：{}", Thread.currentThread().getName());
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= value; i++) {
            list.add(i);
        }
        logger.info("带参数和返回值的异步任务结束执行，线程为：{}", Thread.currentThread().getName());
        return new AsyncResult<>(list);
    }

    @Async
    public void threeAsyncTask(){
        logger.info("模拟异步任务报错，线程为：{}", Thread.currentThread().getName());
        throw new AsyncException("模拟异步任务报错");
    }
}
